package cn.ibizlab.util.adapter.config;

import org.springframework.boot.autoconfigure.web.servlet.WebMvcRegistrations;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;

@Component
public class AdapterWebMvcRegistrations implements WebMvcRegistrations {
    @Override
    public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
        return new CustomRequestMappingHandlerMapping();
    }



    @Configuration
    public class CustomRequestMappingHandlerMapping extends RequestMappingHandlerMapping {


        private Set<String> bootPaths;

        private Pattern pattern = Pattern.compile("\\{[^/]*\\}");

        public Set<String> getBootPaths() {
            if(bootPaths==null) {
                bootPaths = new HashSet<>();
                for(RequestMappingInfo key : getHandlerMethods().keySet()) {
                    Set<String> patterns1 = key.getPatternsCondition().getPatterns();
                    for(String str : patterns1) {
                        String template = pattern.matcher(str).replaceAll("{}");
                        bootPaths.add(template);
                    }
                }
            }
            return bootPaths;
        }

        @Override
        public void unregisterMapping(RequestMappingInfo mapping) {
            try
            {
                Set<String> paths = new HashSet<>();
                Set<String> patterns2 = mapping.getPatternsCondition().getPatterns();
                for(String str : patterns2) {
                    String template = pattern.matcher(str).replaceAll("{}");
                    paths.add(template);
                }
                if(getBootPaths().stream().anyMatch(paths::contains))
                    return;
                super.unregisterMapping(mapping);
            }
            catch (Exception ex)
            {

            }
        }
        @Override
        public void registerMapping(RequestMappingInfo mapping, Object handler, Method method) {
            try
            {
                Set<String> paths = new HashSet<>();
                Set<String> patterns2 = mapping.getPatternsCondition().getPatterns();
                for(String str : patterns2) {
                    String template = pattern.matcher(str).replaceAll("{}");
                    paths.add(template);
                }
                if(getBootPaths().stream().anyMatch(paths::contains))
                    return;
                super.registerMapping(mapping, handler, method);
            }
            catch (Exception ex)
            {

            }
        }


    }
}